package com.polaris.live.ui.party.fragment.game

import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.polaris.live.R.drawable
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.manager.startCountdown
import com.polaris.live.common.network.ApiResponse
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.FragmentPartyGamePlayBaishunBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog_fragment.RoomInvitationFragmentDialog
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.net.liveService
import com.polaris.live.popup.GameTipsPopup
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.InsufficientBalancePopup
import com.polaris.live.popup.PriceModificationPromptPopup
import com.polaris.live.popup.PublicTipsPopup
import com.polaris.live.popup.party.ModifyPricePopup
import com.polaris.live.popup.party.PartyGameBalancePopup
import com.polaris.live.resp.back_resp.PartyGameResp
import com.polaris.live.resp.back_resp.PartyGameSettlementResp
import com.polaris.live.resp.back_resp.PartyGameValidCodeResp
import com.polaris.live.resp.bean.GameExtBean
import com.polaris.live.resp.bean.GameLeisureBean
import com.polaris.live.resp.bean.ZegoGameEventBean
import com.polaris.live.translation.R
import com.polaris.live.ui.party.fragment.base.BaseBaiShunPartyGameFragment
import com.polaris.live.ui.party.listener.GamePlayListener
import com.polaris.live.ui.party.listener.GameSeatViewListener
import com.polaris.live.ui.party.widget.seat.SeatBeanUtil
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.party.game.PartyGamePlayModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 玩游戏Fragment
 * @author Created by 天晴 on 2024/3/13 16:29
 * @since 1.0.0
 **/
class BaiShunGamePlayFragment :
    BaseBaiShunPartyGameFragment<PartyGamePlayModel, FragmentPartyGamePlayBaishunBinding>() {

    private var mLiveInfo: LiveRoomInfo? = null //房间信息
    private var mBaiShunGameExt: PartyGameValidCodeResp? = null //游戏额外信息
    private var mPartyGameInfo: PartyGameResp? = null //单个游戏信息
    private var mMuteSoundVoice = false
    private var mGameStatus = -1  //游戏状态 0 等待中 1已准备好 2进行中  3已结束
    private var mGameSite = 0  //需要的人数
    private var mGamePlayListener: GamePlayListener? = null

    private var mMeInSeat: Boolean = false //自己在座位

    private var mIsMatchCome: Boolean? = null//是否是从匹配过来的
    private var mSoundStatus: Boolean? = null//外部传递过来的麦克风状态
    private var mHomeOwnerIsUp = false//房主在创建完房间后是否上座  如果创建完房间上座了后续就不需要管了

    //是不是房主
    private val mIsAnchor by lazy {
        arguments?.getBoolean(LiveConst.Params.IS_ANCHORID) ?: false
    }

    //结算中界面
    private val mGameBalancePopup by lazy {
        GameTipsPopup(
            requireContext(),
            StringUtils.getString(R.string.game_settlement),
            StringUtils.getString(R.string.game_settlement_tips)
        )
    }

    private var mNowPop: BasePopupView? = null

    private var mOnClickSendGiftCallback: Runnable? = null

    override fun initView(savedInstanceState: Bundle?) {
        mIsMatchCome = arguments?.getBoolean(LiveConst.Params.IS_MATCH_COME_GAME) ?: false
        mSoundStatus = arguments?.getBoolean(LiveConst.Params.SOUND_STATUS) ?: mMuteSoundVoice
        mLiveInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable(LiveConst.Params.LIVE_INFO, LiveRoomInfo::class.java)
        } else {
            arguments?.getParcelable(LiveConst.Params.LIVE_INFO)
        }

        mBinding.apply {
            editBtn.visibility = if (mIsAnchor) View.VISIBLE else View.GONE
            if (resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL) {
                val lp = goinTv.layoutParams as LinearLayout.LayoutParams
                lp.gravity = Gravity.END or Gravity.CENTER_VERTICAL
                goinTv.layoutParams = lp
                jlTv.setBackgroundResource(drawable.rr_r8_e6d1ff)
                jlLl.setBackgroundResource(drawable.ll_r8_back_000000_30)
            }
            if (mIsAnchor) {
                startGame.visibility = View.VISIBLE
            }
        }

        mLiveInfo?.let {
            loadGame(it)
            it.gameStatus?.let { status ->
                updateGameStatus(status)
            }
        }

        mSoundStatus?.let {
            mMuteSoundVoice = it
        }

        initObserve()
        initListener()
    }

    /**
     * 数据变化
     */
    fun updateLiveRoomInfo(name: String, liveInfo: LiveRoomInfo) {
        if (isDestroyView()) {
            return
        }
        withLoaded {
            mLiveInfo = liveInfo
            SeatBeanUtil.getGameSeatId(name)?.let {
                updateSeat(liveInfo, it)
                gameCountDownTime()
            }
            when (name) {
                "gameStatus" -> {
                    liveInfo.gameStatus?.let {
                        updateGameStatus(it)
                    }
                }

                "gameAsset", "gamePrice" -> { //资产类型 //游戏价格
                    updataAsset(liveInfo)
                }

                "gameStartTime" -> {
                    showStartGameBtn()
                    gameCountDownTime()
                    LogExt.logI(
                        TAG,
                        "gameStartTime: liveId = ${mLiveInfo?.liveId}, gameStartTime = ${liveInfo.gameStartTime}"
                    )
                }
            }
        }
    }

    /**
     * 自己是否在游戏中
     */
    fun isGamePlaying(): Boolean {
        return mGameStatus == 2 && areYouPresent()
    }

    /**
     * 显示价格修改
     */
    fun showPriceModificationPromptPopup(message: String) {
        PriceModificationPromptPopup.show(
            requireContext(),
            message
        ) {
            siteUpDown(true)
        }
    }

    private fun updateGameStatus(gameStatus: Int) {
        if (isDestroyView()) {
            return
        }
        LogExt.logI(
            TAG,
            "updateGameStatus   gameStatus:$gameStatus  mGameStatus$mGameStatus    $tag"
        )
        if (mGameStatus == gameStatus) return

        mGameStatus = gameStatus

        showJoinAndExitUi()
        showStartGameBtn()

        when (gameStatus) {
            0 -> {
                popDismiss()
                hideGameUi()
                timerJobCancel()
                mBinding.playTipsTv.text = StringUtils.getString(R.string.game_wait)
                releaseWeb()
                mGamePlayListener?.gamePlayerStop()
                //匹配进来的用户上座
                if (mIsMatchCome == true) {
                    mIsMatchCome = false
                    mLiveInfo?.userId?.let {
                        mViewModel.liveGameSiteUp(it)
                    }
                }
            }

            1 -> {
                popDismiss()
                hideGameUi()
                mBinding.playTipsTv.text = StringUtils.getString(R.string.begin_in_minute)
            }

            2 -> {
                LogExt.logI(TAG, "gameStatus--2---$mLiveInfo")
                releaseWeb()
                mLiveInfo?.let {
                    initGameWeb(it)
                }
                if (areYouPresent()) {
                    mGamePlayListener?.gamePlayerStart()
                }

                showGameUi()
            }

            3 -> {
                popDismiss()
                hideGameUi()
                releaseWeb()
                mGamePlayListener?.gamePlayerStop()
                showPop(mGameBalancePopup)
                mLiveInfo?.liveId?.let {
                    mViewModel.partyGameResult(it)
                }
                mBinding.playTipsTv.text = StringUtils.getString(R.string.in_settlement)
            }

        }
    }

    private var mTimerJob: Job? = null
    private var mRemainingTime = 0L
    private fun startTimer() {
        timerJobCancel()
        val startTime = mLiveInfo?.gameStartTime ?: return
        mRemainingTime = (startTime - CacheUtil.getServerTime()) / 1000
        if (mRemainingTime <= 0) {
            startGo()
            return
        }
        mTimerJob = mViewModel.viewModelScope.startCountdown(mRemainingTime * 1000, 1000L, {
            mBinding.chipLl.visibility = View.INVISIBLE
            mBinding.playTipsTv.text =
                StringUtils.getString(R.string.timer_tips, it / 1000)
                    .convertArabicDigitsToNormal()
        }, {
            if (it <= 0) {
                startGo()
            }
            mBinding.playTipsTv.text = StringUtils.getString(R.string.begin_in_minute)
            mBinding.chipLl.visibility = View.VISIBLE
            if (mTimerJob == coroutineContext[Job]) {
                mTimerJob = null
            }
        })
    }

    /**
     * 取消倒计时
     */
    private fun timerJobCancel() {
        if (isDestroyView()) {
            return
        }
        if (mTimerJob != null) {
            mBinding.chipLl.visibility = View.VISIBLE
            mTimerJob?.cancel()
            mTimerJob = null
        }
    }

    /**
     * 倒计时和点击开始
     */
    private fun startGo() {
        timerJobCancel()
        if (mLiveInfo?.gameStartTime == null) {
            ToastGravity.showGravity(R.string.some_contestants_ready_yet)
            return
        }
        mLiveInfo?.liveId?.let {
            mViewModel.partyGameStart(it, LiveConst.GameBusinessType.LIVE)
        }
    }

    private fun updateSeat(liveInfo: LiveRoomInfo, index: Int) {
        val userStr = SeatBeanUtil.getGameSite(liveInfo, index)
        val userBasicVo = userStr?.let { JsonUtils.fromJson<UserBasicVo>(it) }
        mBinding.playSeatView.upDataItem(index, userBasicVo)

        if (userStr.isNullOrEmpty() || userStr == "null") {
            mBinding.playSeatView.upLoadedItem(index, false)
        } else {
            val load = SeatBeanUtil.getGameLoad(liveInfo, index)
            mBinding.playSeatView.upLoadedItem(index, load == null || !load)
        }

        //判断游戏位上是否包含自己
        if (mBinding.playSeatView.getUsers().contains(UserManager.getUserId().toString())) {
            mBinding.startGame.visibility = View.VISIBLE
        } else {
            if (!mIsAnchor) {
                mBinding.startGame.visibility = View.GONE
            }
        }
    }

    /**
     * 重新加载游戏
     */
    fun reloadGame() {
        if (isDestroyView()) {
            return
        }
        LogExt.logI(TAG, "reloadGame: liveId = ${mLiveInfo?.liveId}")
    }

    /**
     * 加载游戏
     */
    fun loadGame(liveInfo: LiveRoomInfo) {
        if (isDestroyView()) {
            return
        }
        withLoaded {
            mLiveInfo = liveInfo
            loadGameUi(liveInfo)
            liveInfo.gameStatus?.let { status ->
                updateGameStatus(status)
            }
        }
    }

    private fun initGameWeb(liveInfo: LiveRoomInfo) {
        val gameRoomId = liveInfo.gameRoomId ?: return
        val gameType = liveInfo.gameType ?: return

        mViewModel.viewModelScope.launch {
            val data = if (mBaiShunGameExt == null) {
                val data: ApiResponse<PartyGameValidCodeResp> = liveService.getBaiShunGameCodeAndExt(gameType)
                if (!data.isSuccess()) {
                    ToastGravity.showGravity(data.errorMessage)
                    null
                } else {
                    data.result
                }
            } else {
                mBaiShunGameExt
            }
            if (data == null) return@launch
            mBaiShunGameExt = data
            val code = mBaiShunGameExt?.validCode ?: return@launch
            val ext = mBaiShunGameExt?.ext ?: return@launch
            val gameExtBean = JsonUtils.fromJson<GameExtBean>(ext)
            val appChannel = gameExtBean?.appChannel ?: return@launch
            val appId = gameExtBean.appId ?: return@launch

            LogExt.logI(TAG, "222233333  areYouPresent $mLiveInfo  ${areYouPresent()}")
            val role = when {
                mIsAnchor -> 2
                else -> 0
            }
            withContext(CoroutineScopeManager.mainDispatcher) {
                mBinding.gameView.initWebLeisure(
                    requireActivity(), GameLeisureBean(
                        appChannel,
                        appId,
                        liveInfo.gameDownloadUrl ?: "",
                        liveInfo.liveId.toString(),
                        gameExtBean.gsp ?: 101,
                        "",
                        gameExtBean.sceneMode ?: 0,
                        code,
                        "3",
                        mBinding.gameView.getLanguages(),
                        liveInfo.liveId.toString(),
                        UserManager.getUserId().toString(),
                        role,
                        gameRoomId
                    ), this@BaiShunGamePlayFragment
                )
                LogExt.logI(TAG, "initGameWeb: liveId = ${mLiveInfo?.liveId}, isInit = ")

            }

        }

    }

    /**
     * 查询是否在座
     */
    private fun areYouPresent(): Boolean {
        val liveInfo = mLiveInfo
        return if (liveInfo == null) {
            false
        } else {
            for (index in 0 until 7) {
                val userJson = SeatBeanUtil.getGameSite(liveInfo, index)
                if (!userJson.isNullOrEmpty()) {
                    val userBasicVo: UserBasicVo? = JsonUtils.fromJson<UserBasicVo>(userJson)
                    if (userBasicVo != null && userBasicVo.userId == UserManager.getUserId()) {
                        return true
                    }
                }
            }
            false
        }
    }

    private fun releaseWeb() {
        mBinding.gameView.releaseWeb()
    }

    /**
     * 设置数据
     */
    private fun loadGameUi(liveInfo: LiveRoomInfo) {
        if (isDestroyView()) {
            return
        }
        mBinding.apply {
            view?.post {
                view?.let {
                    var nh = 0
                    when (mLiveInfo?.gameType) {
                        LiveConst.GameType.UNOPRO -> {
                            nh = it.width + 80.autoDp
                        }

                        LiveConst.GameType.JELLYBOOM -> {
                            nh = it.width + 80.autoDp
                        }

                        else -> {
                            nh = it.width + 80.autoDp
                        }
                    }
                    mGamePlayListener?.setMessageHeight(it.height - nh - 45.autoDp)
                    val lp2 = gameView.layoutParams as ConstraintLayout.LayoutParams
                    lp2.height = nh
                    gameView.layoutParams = lp2
                }
            }

            gameCoin.text = UserManager.getUser().account?.userGameCoins.formatNumberWithK()
            userAsset.text = UserManager.getUser().account?.userCoins.formatNumberWithK()

            Glide.with(this@BaiShunGamePlayFragment)
                .load(ImageUtils.imgPath(liveInfo.gameLogo))
                .centerCrop()
                .into(logo)
            liveInfo.gameSite?.let {
                mGameSite = it
                playSeatView.setSeatCount(it)
                for (index in 0 until it) {
                    updateSeat(liveInfo, index)
                }
            }
        }
        updataAsset(liveInfo)
        liveInfo.gameStatus?.let { status ->
            updateGameStatus(status)
        }

        if (liveInfo.userId == UserManager.getUserId() && !mHomeOwnerIsUp) {
            if (!mMeInSeat) {
                mBinding.joinBtn.performClick()
            }
            mHomeOwnerIsUp = true
        }

        liveInfo.gameType?.let {
            mViewModel.getOnePartyGame(it)
            mViewModel.getBaiShunGameCode(it)
        }
    }

    /**
     * 更新奖励
     */
    private fun updataAsset(liveInfo: LiveRoomInfo) {
        if (liveInfo.gameAsset == 9) {
            mBinding.freeRl.visibility = View.VISIBLE
            mBinding.assetLl.visibility = View.GONE
        } else {
            mBinding.freeRl.visibility = View.GONE
            mBinding.assetLl.visibility = View.VISIBLE
            mBinding.apply {
                if (liveInfo.gameAsset == 0) {
                    assetType.setImageResource(drawable.icon_diamond)
                } else {
                    assetType.setImageResource(drawable.party_game_mod_yxb2)
                }
                goinTv.text = "${liveInfo.gamePrice}"
            }
        }
    }

    /**
     * 游戏结算  只在房间关闭时处理
     */
    fun gameResult(data: List<PartyGameSettlementResp>) {
        mGameStatus = 3
        showJoinAndExitUi()
        showStartGameBtn()
        hideGameUi()
        releaseWeb()
        mBinding.playTipsTv.text = StringUtils.getString(R.string.in_settlement)
        showPartyGameBalancePopup(data) {
            mGamePlayListener?.gamePlayerStop()
        }
    }

    /**
     * 开始游戏 服务器返回可开始
     */
    private fun startGame() {
        if (mIsAnchor && isCreated()) {

        }
    }

    /**
     * 控制加入退出按钮
     */
    fun showJoinAndExitUi() {
        mBinding.apply {
            if (mMeInSeat) {
                exitGame.visibility = View.VISIBLE
                joinBtn.visibility = View.GONE
            } else {
                exitGame.visibility = View.GONE
                joinBtn.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 游戏倒计时 时间判断条件
     */
    private fun gameCountDownTime() {
        if (mLiveInfo?.gameStartTime != null && mLiveInfo?.gameSite == mBinding.playSeatView.getUsers().size) {
            startTimer()
        } else {
            timerJobCancel()
        }
    }

    /**
     * 控制开启游戏
     */
    private fun showStartGameBtn() {
        val bg = if (mLiveInfo?.gameStartTime == null) {
            drawable.party_go_gray
        } else {
            when (mLiveInfo?.gameType) {
                LiveConst.GameType.LUDO -> drawable.party_go_bg
                LiveConst.GameType.DOMINO -> drawable.party_go_bg2
                LiveConst.GameType.BLACK8 -> drawable.party_go_bg1
                LiveConst.GameType.UNNO -> drawable.party_go_bg1
                LiveConst.GameType.UNOPRO -> drawable.party_go_bg1
                LiveConst.GameType.JELLYBOOM -> drawable.party_go_bg1
                else -> drawable.party_go_bg
            }
        }
        mBinding.startGame.setBackgroundResource(bg)
    }

    private fun initListener() {
        mBinding.apply {
            playSeatView.setOnGameSeatViewListener(object : GameSeatViewListener {
                override fun meChange(seatId: Int?) {
                    mMeInSeat = seatId != null
                    mGamePlayListener?.gamePlayerInSeat(seatId != null)
                    showJoinAndExitUi()
                }

                override fun clickItem(userId: Long?) {
                    if (userId == null) {
                        mLiveInfo?.userId?.let {
                            mViewModel.liveGameSiteUp(it)
                        }
                    } else {
                        mGamePlayListener?.gameSeatClick(userId)
                    }

                }
            })

            startGame.setOnSingleClickListener {
                startGo()
            }

            editBtn.setOnSingleClickListener {
                if (mIsAnchor) {
                    mPartyGameInfo?.let { partyGameInfo ->
                        ModifyPricePopup.show(
                            requireContext(),
                            partyGameInfo,
                            mLiveInfo?.gameAsset,
                            mLiveInfo?.gamePrice
                        ) { type, price ->
                            mLiveInfo?.liveId?.let { userId ->
                                mViewModel.partyGamePrice(userId, price, type)
                            }
                        }
                    } ?: mLiveInfo?.gameType?.let { gameType ->
                        mViewModel.getOnePartyGame(gameType)
                    }
                }
            }
            addDms.setOnSingleClickListener {
                GlobalPopupManager.showRechargePopup(
                    requireContext(),
                    mViewModel,
                    isNeedBottom = true
                )
            }
            exchangeYxb.setOnSingleClickListener {
                showExchangeGamePopup()
            }
            exitGame.setOnSingleClickListener {
                siteUpDown(false)
            }
            btnWen.setOnSingleClickListener {
                mPartyGameInfo?.let { partyGameInfo ->
                    GlobalDialogManager.showGameRuleDialog(
                        requireContext(),
                        partyGameInfo.slogan
                    )
                } ?: mLiveInfo?.gameType?.let { gameType ->
                    mViewModel.getOnePartyGame(gameType)
                }

            }

            btnVoice.setOnSingleClickListener {
                mMuteSoundVoice = !mMuteSoundVoice
            }
            joinBtn.setOnSingleClickListener {
                siteUpDown(true)
            }
            inviteRl.setOnSingleClickListener {
                mLiveInfo?.liveId?.let { liveId ->
                    val fragmentManager = childFragmentManager
                    RoomInvitationFragmentDialog().apply {
                        arguments = bundleOf("liveId" to liveId)
                    }.show(
                        fragmentManager,
                        "RoomInvitationFragmentDialog"
                    )
                }
            }
        }

    }

    fun setOnClickSendGiftCallback(l: Runnable) {
        this.mOnClickSendGiftCallback = l
    }

    /**
     * 上下位置
     */
    fun siteUpDown(boolean: Boolean) {
        mLiveInfo?.let {
            if (boolean) {
                if (mGameStatus != 2) {
                    mViewModel.liveGameSiteUp(it.userId)
                } else {
                    ToastGravity.showGravity(R.string.not_in_operation_time)
                }
            } else {
                if (mMeInSeat) {
                    PublicTipsPopup.show(
                        requireContext(),
                        this,
                        StringUtils.getString(R.string.prompt),
                        StringUtils.getString(R.string.are_you_sure_exit_game_queue),
                        StringUtils.getString(R.string.cancel),
                        StringUtils.getString(R.string.confirm)
                    ) {
                        mViewModel.liveGameSiteDown(it.userId)
                    }
                }
            }
        }

    }

    private fun initObserve() {
        //余额变动
        ImNoticeManager.observeAccountChange(this) {
            mBinding.userAsset.text = UserManager.getUser().account?.userCoins.formatNumberWithK()
        }
        //资产修改
        ImNoticeManager.observeGameAccountChange(this) {
            mBinding.gameCoin.text =
                UserManager.getUser().account?.userGameCoins.formatNumberWithK()
        }
        //上游戏位
        mViewModel.liveGameSiteUpData.observe(this) {
            if (it == 0) return@observe
            mLiveInfo?.gameAsset?.let { type ->
                showInsufficientBalancePopup(type)
                mIsMatchCome = false
            }
        }
        //开始游戏
        mViewModel.partyGameStartData.observe(this) { resultState ->
            if (mIsAnchor) {
                parseState(resultState, {
                    startGame()
                }, {
                    ToastGravity.showGravity(it.errorMsg)
                })
            }
        }

        //获取单个派对游戏
        mViewModel.getOnePartyGameData.observe(this) { resultState ->
            parseState(resultState, {
                mPartyGameInfo = it
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        //获取游戏校验码
        mViewModel.getBaiShunGameExtData.observe(this) { resultState ->
            parseState(resultState, {
                mBaiShunGameExt = it
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        //修改价格
        mViewModel.partyGamePriceData.observe(this) { resultState ->
            if (mIsAnchor) {
                parseState(resultState, {
                    ToastGravity.showGravity(R.string.modified_successfully)
                }, {
                    ToastGravity.showGravity(it.errorMsg)
                })
            }
        }
        //游戏结算
        mViewModel.partyGameResultData.observe(this) { resultState ->
            parseState(resultState, {
                showPartyGameBalancePopup(it)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun showPartyGameBalancePopup(data: List<PartyGameSettlementResp>, onDismiss: (() -> Unit)? = null) {
        popDismiss()
        PartyGameBalancePopup.show(
            requireContext(),
            mLiveInfo?.gameEndWaitSecond ?: 0,
            data,
            {
                siteUpDown(true)
            },
            {
                siteUpDown(true)
            }, onDismiss
        )
    }

    override fun onResume() {
        super.onResume()
        mBinding.gameView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.gameView.onPause()
    }

    override fun onDestroyView() {
        timerJobCancel()
        mBinding.gameView.onDestroy()
        super.onDestroyView()
    }

    fun setGamePlayListener(listener: GamePlayListener) {
        mGamePlayListener = listener
    }

    private fun showPop(pop: BasePopupView) {
        popDismiss()
        mNowPop = XPopup.Builder(context)
            .isViewMode(true)
            .isDestroyOnDismiss(true)
            .asCustom(pop)
            .show()
    }

    private fun popDismiss() {
        mNowPop?.dismiss()
    }

    private fun showGameUi() {
        mBinding.startCl.visibility = View.GONE
        mBinding.gameView.visibility = View.VISIBLE
    }

    private fun hideGameUi() {
        mBinding.startCl.visibility = View.VISIBLE
        mBinding.gameView.visibility = View.INVISIBLE
    }

    fun exitRoom() {
        if (isDestroyView()) {
            return
        }
        releaseWeb()
        popDismiss()
        mGameStatus = 0
        mBinding.startCl.visibility = View.VISIBLE
        mBinding.gameView.visibility = View.INVISIBLE
    }

    /**
     * 余额不足弹窗
     */
    private fun showInsufficientBalancePopup(type: Int) {
        LogExt.logI("GamePlayFragment", "222233333     $type")

        XPopup.Builder(context)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(InsufficientBalancePopup(requireContext(), type, {
                GlobalPopupManager.showRechargePopup(requireContext(), mViewModel, isNeedBottom = true)
            }, {
                showExchangeGamePopup()
            }))
            .show()
    }

    /**
     * 显示兑换游戏币
     */
    private fun showExchangeGamePopup() {
        GlobalPopupManager.showExchangeGamePopup(requireContext(), mViewModel)
    }

    /**
     * =====================游戏回调============================
     */
    override fun gameLoading() {
        reportEvent(0, "0")
    }

    override fun gameLoaded() {
        reportEvent(1, "1")
    }

    override fun recharge() {
    }

    override fun destroy() {
    }

    override fun sendGameAction(type: Int) {
    }

    private fun reportEvent(event: Int, params: Any) {
        val info = mLiveInfo ?: return

        val finalParams = if (params is String) {
            params
        } else {
            JsonUtils.toJson(params)
        }

        mViewModel.baiShunGameEvent(
            ZegoGameEventBean(
                info.liveId,
                LiveConst.GameBusinessType.LIVE,
                event,
                finalParams
            )
        )
    }

    companion object {

        const val TAG = "BaiShunGamePlayFragment"
        const val GAME_TIME = 5000L //等待結算时间
    }
}